/**
 * 
 */
package pvt.delez.pa.depend;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ImportDeclaration;

import pam.JarLibrary;
import pam.PamFactory;


/**
 * 依赖第三方包分析 <br/>
 * 通过JDT/AST对java文件中的import进行提取． 再通过Library分析其中目录结构，　进行适配，　并找到使用／引用的包
 * (去除了第三方依赖包)
 * 
 * @author Administrator
 * 
 */
public class AnalysisLibraryDepend {
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// Get the root of the workspace
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		IWorkspaceRoot root = workspace.getRoot();
		// Get all projects in the workspace
		IProject[] projects = root.getProjects();
		// Loop over all projects
		for (IProject project : projects) {
			try {
				if (project.isNatureEnabled("org.eclipse.jdt.core.javanature")) {
					IJavaProject javaProject = JavaCore.create(project);
					analysis(javaProject);
				}
			} catch (CoreException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public void analysis(IProject project) throws CoreException,
			JavaModelException {
		System.out.println("Working in project " + project.getName());
		// Check if we have a Java project
		if (project.isNatureEnabled("org.eclipse.jdt.core.javanature")) {
			IJavaProject javaProject = JavaCore.create(project);
			analysis(javaProject);
		}
	}

	public void analysis(IJavaProject javaProject)
			throws JavaModelException {
		IPackageFragment[] packages = javaProject.getPackageFragments();
		
		List<IPackageFragment> pkgInsource = new ArrayList<IPackageFragment>();
		Map<String, JarLibrary> pkgInLibrary = new HashMap<String, JarLibrary>();
		Map<String, JarLibrary> libraries = new HashMap<String, JarLibrary>();

		for (IPackageFragment mypackage : packages) {

			if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) {
				pkgInsource.add(mypackage);
				
			}else if(mypackage.getPath().isValidSegment("jre")){
				IPath path = mypackage.getPath();
				String libName = path.lastSegment();
				
				JarLibrary lib = libraries.get(libName);
				if(lib == null){
					lib = PamFactory.eINSTANCE.createJarLibrary();

					lib.setName(libName);
					lib.setPath(path.toString());
					libraries.put(libName, lib);
					
				}


				pkgInLibrary.put(mypackage.getElementName(), lib);
			}

		}
		for (IPackageFragment frg : pkgInsource) {
			analysis(frg, pkgInLibrary);
		}
	}

	private void analysis(IPackageFragment mypackage, Map<String, JarLibrary> pkgInLibrary)
			throws JavaModelException {
		for (ICompilationUnit unit : mypackage.getCompilationUnits()) {
//			org.eclipse.jface.text.Document doc = new org.eclipse.jface.text.Document(unit.getSource());
//			System.out
//					.println("Has number of lines: " + doc.getNumberOfLines());
			analysis(unit, pkgInLibrary);

		}
	}

	private void analysis(ICompilationUnit unit, Map<String, JarLibrary> pkgInLibrary) throws JavaModelException {
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setSource(unit);
		parser.setResolveBindings(true);
		CompilationUnit parse =  (CompilationUnit) parser.createAST(null); // parse
		List<ImportDeclaration> imports = parse.imports();
		for (ImportDeclaration declare : imports) {
			String name = declare.getName().getFullyQualifiedName();
			if(!name.startsWith("java"))
			{
				String pkgName = name.substring(0, name.lastIndexOf('.'));//xxx.xx.x.X or xxx.xx.x.*
				System.out.println(pkgInLibrary.get(pkgName));
			}
			System.out.println("import = " + declare.getName() + declare.getFlags());
		}
	}

}
